<script setup lang="ts">
import type { TableInstance } from 'element-plus'

import { Delete, Edit } from '@element-plus/icons-vue'
import type { TableColumnProps } from '../'
import type { ApplicationModel } from '@/types/modules/application-models'

const props = withDefaults(
  defineProps<{
    loading: boolean
    columns: TableColumnProps[]
    lists: ApplicationModel[]
  }>(),
  {},
)

const emits = defineEmits<{
  (e: 'select-change', value: ApplicationModel | null): void
  (e: 'edit', value: ApplicationModel): void
  (e: 'delete', value: ApplicationModel): void
}>()

const tableRef = ref<TableInstance>()
const [current, setCurrent]
  = useState<ApplicationModel | null>(null)

function selectHandler(row: ApplicationModel) {
  tableRef.value?.clearSelection()
  tableRef.value?.toggleRowSelection(row, true)
  setCurrent(row)
  emits('select-change', row)
}

watch(
  () => props.lists,
  () => {
    if (unref(current)) {
      const target = unref(props.lists).find(
        item => item.id === unref(current)!.id,
      )
      if (target) {
        // 当重新获取模型列表时，列表渲染完成后重新选中模型
        nextTick(() => {
          tableRef.value?.clearSelection()
          tableRef.value?.toggleRowSelection(target, true)
        })
      }
      else {
        // 新的模型列表中没有当前选中的模型
        // 默认选中第一个(如果存在)
        nextTick(() => {
          const head = unref(props.lists)[0] ?? null
          if (head) {
            tableRef.value?.clearSelection()
            tableRef.value?.toggleRowSelection(head, true)
          }
          setCurrent(head)
          emits('select-change', head)
        })
      }
    }
  },
  {
    immediate: true,
  },
)

defineExpose({
  current,
})
</script>

<template>
  <ElTable
    ref="tableRef"
    v-loading="loading"
    element-loading-custom-class="global-loading"
    :data="lists"
    height="100%"
    highlight-current-row
    border
    current-row-key="id"
    @select="(_, row) => selectHandler(row)"
    @row-click="row => selectHandler(row)"
  >
    <template #empty>
      <TableEmpty />
    </template>
    <ElTableColumn
      fixed
      type="selection"
      :width="40"
    />
    <ElTableColumn
      v-for="column in columns"
      :key="column.prop"
      v-bind="column"
      show-overflow-tooltip
    />
    <ElTableColumn label="操作" prop="id" :width="120">
      <template #default="{ row }">
        <TdButton
          title="编辑"
          :icon="Edit"
          type="primary"
          @click="emits('edit', row)"
        />
        <el-divider direction="vertical" />
        <TdButton
          title="删除"
          :icon="Delete"
          type="danger"
          @click="emits('delete', row)"
        />
      </template>
    </ElTableColumn>
  </ElTable>
</template>

<style scoped>
:deep(.el-table__header .el-checkbox) {
  display: none;
}
</style>
